package com.yupi.springbootinit.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.constant.Leisure;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.LeisuresiteMapper;
import com.yupi.springbootinit.model.dto.site.SiteUpdateRequest;
import com.yupi.springbootinit.model.entity.Leisuresite;
import com.yupi.springbootinit.model.entity.Site;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.service.LeisuresiteService;
import com.yupi.springbootinit.service.SiteService;
import com.yupi.springbootinit.mapper.SiteMapper;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Lenovo
 * @description 针对表【site(场地信息表)】的数据库操作Service实现
 * @createDate 2024-04-27 13:30:49
 */
@Service
@Slf4j
public class SiteServiceImpl extends ServiceImpl<SiteMapper, Site>
        implements SiteService {

    @Autowired
    private LeisuresiteService leisuresiteService;
    @Autowired
    private SiteMapper siteMapper;
    @Autowired
    private LeisuresiteMapper leisuresiteMapper;
    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public Site addSite(Integer siteName, Integer belongs, Integer siteArea, String sitetMain) {
        //1、创建新site对象，存入site表中
        Site site = new Site();
        site.setSiteName(siteName);
        site.setBelongs(belongs);
        site.setSiteArea(siteArea);
        site.setSitetMain(sitetMain);
        //新增场地信息到场地表中
        boolean result = this.save(site);
        if (!result) { // 保存失败
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //2、在空闲表中也增加
        Leisuresite leisuresite = new Leisuresite();

        leisuresite.setSiteName(siteName);
        leisuresite.setBelongs(belongs);
        //设置时间。空闲开始时间

        Calendar startcalendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月-dd日HH:mm:ss");
        String timestamp = formatter.format(startcalendar.getTime());
        System.out.println("========startcalendar=====" + timestamp);


        //设置结束时间。默认新增的场地都是空闲的  空闲2小时
        Calendar endcalendar = Calendar.getInstance();
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy年-MM月-dd日HH:mm:ss");
        String timestamp2 = formatter2.format(endcalendar.getTime());
        System.out.println("========endcalendar=====" + timestamp2);
        //获取当前小时数
        LocalTime localTime = LocalTime.now();
        int hour1 = localTime.getHour();
        endcalendar.set(Calendar.HOUR, hour1 + 2);
        System.out.println("修改后的hour" + endcalendar.get(Calendar.HOUR));


//        LocalTime time = LocalTime.now();
////        System.out.println(time);          // 输出: 16:21:23.849
//        int hour = time.getHour();
//        int endHour =hour+2;


//        Calendar endcalendar=Calendar.getInstance();
//        endcalendar.set(Calendar.YEAR,2024);
//        endcalendar.set(2024,4,27,endHour,4);

        leisuresite.setFreeStartTime(startcalendar.getTime());
        leisuresite.setFreeEndTime(endcalendar.getTime());
        leisuresite.setStatus(Leisure.LeisureStatus1);
        boolean savelei = leisuresiteService.save(leisuresite);
        if (!savelei) { // 保存失败
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        return null;
    }

    /**
     * 修改场地空闲信息
     *
     * @param site
     * @return
     */
    @Transactional
    @Override
    public boolean updateFreeTime(SiteUpdateRequest site) throws ParseException {// TODO: 2024/5/2 时间在数据库中，小时数不对。
        Long id = site.getId();
        Integer siteName = site.getSiteName();
        Integer belongs = site.getBelongs();
        Integer siteArea = site.getSiteArea();
        String siteMain = site.getSiteMain();
        Date freeStartTime = site.getFreeStartTime();
        Date freeEndTime = site.getFreeEndTime();
        Integer status = site.getStatus();
//        log.info(freeEndTime.getTime());
        System.out.println(freeEndTime.getTime());

        //查询之前的site信息
        Site resultSite = this.getById(id);

        Integer ressiteName = resultSite.getSiteName();
        Integer resbelongs = resultSite.getBelongs();
        Integer ressiteArea = resultSite.getSiteArea();
        String ressitetMain = resultSite.getSitetMain();

        //修改了site的基本信息。需要在site表和空闲表都做修改x有修改其他内容
        if (siteName != ressiteName || belongs != resbelongs || siteArea != ressiteArea || !siteMain.equals(ressitetMain)) {
            //创建一个新的site对象，设置值，进行更新
            Site site1 = new Site();
            site1.setSiteName(siteName);
            site1.setBelongs(belongs);
            site1.setId(id);
            site1.setSiteArea(siteArea);
            site1.setSitetMain(siteMain);
            //1、先修改site表
            int i = siteMapper.updateById(site1);
            if (i == 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
        }

        //修改空闲信息表信息
        Leisuresite leisuresite = new Leisuresite();
        leisuresite.setSiteName(siteName);
        leisuresite.setBelongs(belongs);

//        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月-dd日HH:mm:ss");
        String timestamp = formatter.format(freeStartTime);
        log.info("当前时间的时间戳，转换后：{}", timestamp);
        //将timestamp转换为Date类型
        Date resdate = formatter.parse(timestamp); // TODO: 2024/4/30 解析时间出错
        log.info("当前时间的转换后的date时间为：" + resdate);


        //结束时间设置
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(freeEndTime);
//        calendar.add(Calendar.HOUR, 2);
        Date endtime = calendar.getTime();
        log.info("新设置的结束时间：{}", endtime);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年-MM月-dd日HH:mm:ss");

        leisuresite.setFreeStartTime(resdate);
        leisuresite.setFreeEndTime(endtime);
        leisuresite.setId(id);
        leisuresite.setStatus(status);

        //2、再修改空闲表
        int i = leisuresiteMapper.updateById(leisuresite);
        if (i <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        return true;
    }

    @Override
    public List<Site> getAllSite(HttpServletRequest request) {
//        User loginUser = userService.getLoginUser(request);
//        this.baseMapper.
        List<Site> sites = siteMapper.selectList(new QueryWrapper<Site>().eq("isdelete",0));
        return sites;
    }


}




